from c_code import obj_c_tools
import copy
import config
import os

doc1 = config.read_json(f"{config.path}/locale/config.json")["doc"]
dict_icon = {"doc": doc1}


def merge_twoDict(a, b):
    return dict(a, **b)


def searhc_icon(name):
    name = name + ".png"
    dict_icon = {}
    path = "/usr/share/icons/HighContrast"
    for dir1 in os.listdir(path):
        if os.path.isdir(f"{path}/{dir1}"):
            list_png = os.listdir(f"{path}/{dir1}/apps")
            if name in list_png:
                index = dir1.find("x")
                if index != -1:
                    dict_icon[int(dir1[0:index])] = f"{path}/{dir1}/apps/{name}"
    return dict_icon


def pars_file():
    dict_icon["icon"] = []
    dict_icon["call"] = {}

    len_struct = obj_c_tools.len_struct()
    for i in range(0, len_struct):
        dict_exec = {}
        struct_data = obj_c_tools.get_data(i)
        str_UBL = struct_data.X_UBLHelpPage.decode().replace("\n", "")
        icon = struct_data.Icon.decode().replace("\n", "")
        struct_data.Icon.decode().replace("\n", "")
        name = ""
        categories = struct_data.Categories.decode().replace("\n", "")
        categories_flag = []
        if config.lang_os == "ru_RU":
            name = struct_data.Name_ru.decode().replace("\n", "")
        else:
            name = struct_data.Name.decode()
        if categories.find("X-UBL-SettingsManager;X-UBL-PersonalSettings") != -1:
            categories_flag.append("Личные")
        elif categories.find("X-UBL-SettingsManager;X-UBL-HardwareSettings") != -1:
            categories_flag.append("Оборудование")
        elif categories.find("X-UBL-SettingsManager;X-UBL-SystemSettings") != -1:
            categories_flag.append("Система")
        elif categories.find("X-UBL-SettingsManager") != -1:
            categories_flag.append("Прочее")
        # print(name)
        dict_info = {
            "text": name,
            "Categories": categories_flag,
            "icon": searhc_icon(icon),
        }
        dict_icon["icon"].append(dict_info)
        exec_str = struct_data.Exec.decode().replace("\n", "")
        dict_exec = {name: {"call_app": exec_str, "link": str_UBL}}
        if len(dict_icon["call"]):
            dict_icon["call"] = merge_twoDict(dict_icon["call"], dict_exec)
        else:

            dict_icon["call"] = dict_exec
    config.write_json(f"{config.path}/locale/config.json", dict_icon)


pars_file()
